<?php
namespace app\common\model\sharewifi;

use hema\wechat\Map;
use hema\wechat\Wxapp;

/**
 * 门店模型
 */
class Shop extends BaseModel
{
    // 定义表名
    protected $name = 'sharewifi_shop';
    // 定义主键
    protected $pk = 'shop_id';
    // 追加字段
    protected $append = ['qrcode','score','conn_succ','conn_fail'];
    
    /**
     * 关联商品分类表
     */
    public function category()
    {
        return $this->belongsTo('app\\common\\model\\sharewifi\\Category','category_id');
    }
    
    /**
     * 评分
     */
    public function getScoreAttr($value)
    {
        return 5.0;
    }
    /**
     * 联网成功
     */
    public function getConnSuccAttr($value,$data)
    {
        return Connect::where('is_success',1)->where('shop_id',$data['shop_id'])->count();
    }
    /**
     * 联网失败
     */
    public function getConnFailAttr($value,$data)
    {
        return Connect::where('is_success',0)->where('shop_id',$data['shop_id'])->count();
    }
    
    /**
     * 小程序码
     */
    public function getQrcodeAttr($value,$data)
    {
        return base_url() . 'qrcode/sharewifi/shop-' . $data['shop_id'] . '.png';
    }

    /**
     * 门店头像
     */
    public function getLogoAttr($value)
    {
        if(empty($value)){
             return base_url() . 'assets/img/no_pic.jpg';
        }
        return uploads_url() . '/' . $value;
    }
    
    /**
     * 状态
     */
    public function getStatusAttr($value)
    {
        $status = ['关闭', '开启'];
        return ['text' => $status[$value], 'value' => $value];
    }
   
    /**
     * 获取我的列表
     * $is_category 是否分类
     */
    public function getList($is_category=0,$user_id=0,$location='')
    {
        $model = $this->with(['category'])->order('shop_id','desc');
        $filter = [];
        //用户获取
        if($user_id > 0){
            $filter['user_id'] = $user_id;
        }else{
            if($is_category == 0){
                $filter['category_id'] = 0; //未分类
            }else{
                $model->where('category_id','>',0);//已分类
            }
        }
        $list = $model->where($filter)
            ->paginate(['list_rows'=>15,'query' => request()->param()]);
        //是否计算距离
        if(!empty($location)){
            $to = $this->column('location');
            $to = implode(';',$to);
            $map = new Map;
            if($result = $map->getDistance($location,$to)){
                for($n=0;$n<sizeof($list);$n++){
                    $distance = $result[$n]['distance'];
                    if($distance >= 1000){
                        $range = sprintf("%.2f", $distance/1000) . 'km';
                    }else{
                        $range = $distance . 'm';
                    }
                    $list[$n]['distance'] = $distance;
                    $list[$n]['range'] = $range;
                }
                //$list = arr_sort($list,'distance','asc');
            }
        }
        return $list;
    }

    /**
     * 接口获取的列表
     */
    public function apiList($category_id=0,$sortType='location',$location='')
    {
        $filter = [
            'status' => 1    
        ];
        $category_id > 0 && $filter['category_id'] = $category_id;
        // 排序规则
        $sort = [];
        if ($sortType === 'top') {
            $sort = ['sort', 'shop_id' => 'desc'];
        } elseif ($sortType === 'visit') {
            $sort = ['visit' => 'desc'];
        }
        $list = $this->with(['category'])
            ->where($filter)
            ->order($sort)
            ->select()
            ->toArray();
        //是否计算距离
        if(!empty($location) and $list){
            $map = new Map;
            $length = sizeof($list);
            $x = 0; //步骤长200
            $toArray = [];//
            while($x < $length){
                $to = '';
                for($n=$x;$n<$length;$n++){
                    if($n == $x + 200){
                       break; 
                    }
                    if(!empty($list[$n]['location'])){
                        if(!empty($to)){
                           $to .= ';' . $list[$n]['location'];
                        }else{
                            $to .= $list[$n]['location'];
                        }
                    }
                }
                if($result = $map->getDistance($location,$to)){
                    $rs_n = 0;
                    for($n=$x;$n<$length;$n++){
                        if($n == $x + 200){
                           break; 
                        }
                        if(!empty($list[$n]['location'])){
                            $distance = $result[$rs_n]['distance'];
                            if($distance >= 1000){
                                $range = sprintf("%.2f", $distance/1000) . 'km';
                            }else{
                                $range = $distance . 'm';
                            }
                            $list[$n]['distance'] = $distance;
                            $list[$n]['range'] = $range;
                        }
                        $rs_n = $rs_n + 1;
                    }
                }
                $x = $x + 200;  
            }
            if($sortType=='location'){
                $list = arr_sort($list,'distance','asc');
            }
        }
        return $list;
    }
    /**
     * 获取详情
     */
    public static function detail($shop_id=0, string $location = '')
    {
        $detail = self::with(['category'])->find($shop_id);
        if(!empty($location)){
            $map = new Map;
            if($result = $map->getDistance($location,$detail['location'])){
                $distance = $result[0]['distance'];
                if($distance >= 1000){
                    $range = sprintf("%.2f", $distance/1000) . 'km';
                }else{
                    $range = $distance . 'm';
                }
                $detail['distance'] = $distance;
                $detail['range'] = $range;
            }
        }
        return $detail;
    }

     /**
     * 添加
     */
    public function add($data,$user_id)
    {
        $data['user_id'] = $user_id;
        $this->save($data);
        $wx = new Wxapp(get_addons_config('sharewifi'));
        if(!$wx->getUnlimitedQRCode('sharewifi','shop-' . $this->shop_id,'pages/shop/wifi')){
            $this->error = $wx->getError();
            return false;
        }
        return true;
    }
    
    
    /**
     * 编辑
     */
    public function edit($data)
    {
        $wx = new Wxapp(get_addons_config('sharewifi'));
        if(!$wx->getUnlimitedQRCode('sharewifi','shop-' . $this->shop_id,'pages/shop/wifi')){
            $this->error = $wx->getError();
            return false;
        }
        return $this->save($data) !== false;
    }
    
    /**
     * 删除
     */
    public function remove()
    {
        $file = './qrcode/sharewifi/shop-' . $this->shop_id . '.png';
        if(file_exists($file)){
            @unlink($file);
        }
        return $this->delete();
    }
    
    /**
     * 状态
     */
    public function status()
    {
        if($this->status['value'] == 1){
            $this->status = 0;
        }else{
            $this->status = 1;
        } 
        return $this->save();
    }
}